<script setup>
import { onMounted, ref, watch } from 'vue';
import { useDepartmentSelectStore } from '../../../store/departmentSelect';
import department from '../../../api/department';
import { useAddUserStore } from '../../../store/addUser';
import { usePositionSelectStore } from '../../../store/positionSelect';
import position from '../../../api/position';
const addUserStore = useAddUserStore();
const departmentSelectStore = useDepartmentSelectStore();
const positionSelectStore = usePositionSelectStore();
// 配置树形组件属性
const treeProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}
watch(
  () => addUserStore.user.departmentId,
  async (newVal) => {
    if (newVal) {
      await position.getPositionSelect(newVal)
        .then(res => positionSelectStore.setpositionSelect(res.data.data))
        .catch(err => console.error(err));
    } else {
      positionSelectStore.setpositionSelectNull();
      addUserStore.user.positionId = null;
    }
  },
  { immediate: true } // 初始化时立即触发
);
const handleDepartmentChange = async () => {
  if (addUserStore.user.departmentId) {
    console.log(addUserStore.user.departmentId);
    // 获取岗位数据
    await position.getPositionSelect(addUserStore.user.departmentId).then((res) => {
      positionSelectStore.setpositionSelect(res.data.data);
      console.log(positionSelectStore.positionSelect);
    }).catch((err) => {
      console.log(err);
    });
  } else {
    positionSelectStore.setpositionSelectNull(); // 清空岗位选项
    addUserStore.user.positionId = null;
  }
};
onMounted(async () => {
  await department.getDepartmentSelect().then((res) => {
    departmentSelectStore.setDepartmentSelect(res.data.data);
  }).catch((err) => {
    console.log(err);
  });
});
</script>
<template>
  <el-tree-select :check-on-click-node="true" v-if="departmentSelectStore.departmentSelect.length > 0"
    @change="handleDepartmentChange" :props="treeProps" node-key="value" v-model="addUserStore.user.departmentId"
    check-strictly clearable :data="departmentSelectStore.departmentSelect" :render-after-expand="false" />
</template>
<style scoped></style>